import {db} from '../database/db';
import {SysRole} from '../domain/sys_role';

export const SysRoleDao = {
    getRoles: async (offset: number | string = 0, limit: number | string = 10) => {
        const baseQuery = db.selectFrom('sys_role').where('del_flag', '=', '0');
        const [{count}] = await baseQuery.select(db.fn.countAll().as('count')).execute();
        const total = Number(count);
        if (total === 0) {
            return {list: [], total: 0};
        }
        const list = await baseQuery
            .selectAll()
            .orderBy('role_sort', 'asc')
            .offset(Number(offset))
            .limit(Number(limit))
            .execute();
        return {list, total};
    },

    getRoleOptions: async () => {
        return await db.selectFrom('sys_role')
            .select(['role_id', 'role_name'])
            .where('del_flag', '=', '0')
            .orderBy('role_sort', 'asc')
            .execute();
    },

    getRoleById: async (role_id: number) => {
        return await db.selectFrom('sys_role')
            .selectAll()
            .where('role_id', '=', role_id)
            .executeTakeFirst();
    },

    createRole: async (data: SysRole) => {
        const result = await db.insertInto('sys_role').values(data as any).executeTakeFirst();
        return Number((result as any).insertId);
    },

    updateRole: async (role_id: number, data: Partial<SysRole>) => {
        const result = await db.updateTable('sys_role')
            .set(data)
            .where('role_id', '=', role_id)
            .executeTakeFirst();
        return Number((result as any).numUpdatedRows);
    },

    deleteRole: async (role_id: number) => {
        const result = await db.updateTable('sys_role')
            .set({del_flag: '2'})
            .where('role_id', '=', role_id)
            .executeTakeFirst();
        return Number((result as any).numUpdatedRows);
    }
}
 